home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 2.toast / pc / sample code / quicktime / wired movies and sprites / desktopsprites.win / imagecompressionutilities.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-06  |  27.8 KB  |  879 lines

  1. /*
  2.     File:        ImageCompressionUtilities.c
  3.     
  4.     Description: Image Compression Utilities
  5.  
  6.     Author:        Peter Hoddie, Sean Allen, Chris Flick
  7.     Revised by: Tim Monroe
  8.  
  9.     Copyright:     © Copyright 1999 Apple Computer, Inc. All rights reserved.
  10.     
  11.     Disclaimer:    IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
  12.                 ("Apple") in consideration of your agreement to the following terms, and your
  13.                 use, installation, modification or redistribution of this Apple software
  14.                 constitutes acceptance of these terms.  If you do not agree with these terms,
  15.                 please do not use, install, modify or redistribute this Apple software.
  16.  
  17.                 In consideration of your agreement to abide by the following terms, and subject
  18.                 to these terms, Apple grants you a personal, non-exclusive license, under Apple’s
  19.                 copyrights in this original Apple software (the "Apple Software"), to use,
  20.                 reproduce, modify and redistribute the Apple Software, with or without
  21.                 modifications, in source and/or binary forms; provided that if you redistribute
  22.                 the Apple Software in its entirety and without modifications, you must retain
  23.                 this notice and the following text and disclaimers in all such redistributions of
  24.                 the Apple Software.  Neither the name, trademarks, service marks or logos of
  25.                 Apple Computer, Inc. may be used to endorse or promote products derived from the
  26.                 Apple Software without specific prior written permission from Apple.  Except as
  27.                 expressly stated in this notice, no other rights or licenses, express or implied,
  28.                 are granted by Apple herein, including but not limited to any patent rights that
  29.                 may be infringed by your derivative works or by other works in which the Apple
  30.                 Software may be incorporated.
  31.  
  32.                 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
  33.                 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
  34.                 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  35.                 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
  36.                 COMBINATION WITH YOUR PRODUCTS.
  37.  
  38.                 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
  39.                 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  40.                 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  41.                 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
  42.                 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
  43.                 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
  44.                 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45.                 
  46.     Change History (most recent first):
  47.  
  48.        <5>         08/30/00    srk        Carbonization
  49.        <4>         12/16/98    rtm        removed orphaned prototype for compressTransparentRLEwithHitTesting
  50.        <3>         05/28/98    rtm        added some typecasting to minimize MSDev compiler warnings
  51.        <2>         03/22/98    rtm        made changes to RecompressPictureFileWithTransparency, as per Chris' fixes
  52.        <1>         03/27/98    rtm        existing file
  53.  
  54. */
  55.  
  56.  
  57. /************************************************************
  58. *                                                           *
  59. *    INCLUDE FILES                                          *
  60. *                                                           *
  61. *************************************************************/
  62.  
  63.  
  64. #ifndef _IMAGECOMPRESSIONUTILITIES_
  65. #include "ImageCompressionUtilities.h"
  66.  
  67. /************************************************************
  68. *                                                           *
  69. *    PROTOTYPES                                             *
  70. *                                                           *
  71. *************************************************************/
  72.  
  73. static pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags );
  74. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap );
  75. static void DrawPictureNoDither(PicHandle pic, const Rect *bounds);
  76. static OSErr prepareFor16BitCompress(PicHandle *pic);
  77. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  78. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  79.  
  80.  
  81. /************************************************************
  82. *                                                           *
  83. *    CONSTANTS                                              *
  84. *                                                           *
  85. *************************************************************/
  86.  
  87. // We use the Animation compressor at 16 bit depth in these utilities
  88. #define kCompressDepth    16
  89.  
  90. // A few macros to help with error handling
  91. #define        BailIf(a, e)         {if (a)     { err = e; goto bail; }}
  92. #define        BailOSErr(a)         {if ((err = a) != noErr)    goto bail;}
  93. #define        BailMemErr(a)        {a; if ((err = MemError()) != noErr) goto bail;}
  94.  
  95. /************************************************************
  96. *                                                           *
  97. *    STRUCTURES                                             *
  98. *                                                           *
  99. *************************************************************/
  100.  
  101. // Used for compressing QuickDraw pictures with transparency/hittesting
  102.  
  103. typedef struct {
  104.     PicHandle    picture;
  105. } PictureCompressProcData;
  106.  
  107.  
  108. // Used for recompressing QuickTime compressed data with transparency/hittesting
  109.  
  110. typedef struct {
  111.     ImageDescriptionHandle    imageDesc;
  112.     Handle                    imageData;
  113. } CompressedImageCompressProcData;
  114.  
  115.  
  116. typedef struct {
  117.     CGrafPtr tempPort;
  118.  
  119.     Handle data;
  120.     ImageDescriptionHandle idh;
  121. } extractPictRecord;
  122.  
  123.  
  124.  
  125.  
  126. // PICT to compressed image conversion
  127.  
  128. //    Given a QuickDraw picture, extract QuickTime compressed image data and description, if any.
  129. //
  130. //    It does this by creating a temporary CGrafPort, installing a QuickDraw bottleneck
  131. //    routine for the StdPix call, and then drawing the picture. Since this routine will
  132. //    be called whenever QuickTime compressed image data is encountered, it can
  133. //    stash away any found compressed data and description. On DrawPicture's return, the
  134. //    stashed data and description is retrieved and returned to the caller.
  135. //
  136. //    Worth noting in this utility is definition of the extractPictRecord. This is a 
  137. //    structure consisting of a CGrafPort structure followed by fields for a handle to 
  138. //    image data and an ImageDescription. This layout allows ExtractCompressData to open
  139. //    a CGrafPort using the embedded CGrafPort field, and set this as the current port. 
  140. //    Then, in the StdPix routine extractStdPix, the current port can be retrieved and 
  141. //    cast to a pointer to an extractPictRecord to get access to the other fields.
  142. //
  143.  
  144.  
  145. OSErr ExtractCompressData( PicHandle thePict, Handle *dataOut, ImageDescriptionHandle *idh )
  146. {
  147.     OSErr                err = noErr;
  148.     extractPictRecord     state;
  149.     CQDProcs             procs;
  150.     GrafPtr             savePort;
  151.     Rect                 bounds;
  152.  
  153.     if ( dataOut )
  154.         *dataOut = nil;
  155.     if ( idh )
  156.         *idh = nil;
  157.  
  158.     GetPort( &savePort );
  159. #ifdef TARGET_OS_WIN32
  160.     state.tempPort = (CGrafPtr)NewPtr(sizeof(CGrafPort));
  161.     OpenCPort(state.tempPort);
  162. #else
  163.     state.tempPort = CreateNewPort();
  164. #endif
  165.     SetStdCProcs( &procs );
  166.     procs.newProc1 = (UniversalProcPtr)NewStdPixUPP(extractStdPix);
  167. #ifdef TARGET_OS_WIN32
  168.     state.tempPort->grafProcs = &procs;
  169. #else
  170.     SetPortGrafProcs(state.tempPort, &procs);
  171. #endif
  172.  
  173.  
  174.     state.data = nil;
  175.     state.idh = nil;
  176.  
  177.     MacSetPort( (GrafPtr)state.tempPort );
  178.     HidePen();
  179.  
  180.     bounds = (**thePict).picFrame;
  181.     DrawPicture(thePict, &bounds);    
  182.  
  183.     MacSetPort( savePort );
  184. #ifdef TARGET_OS_WIN32
  185.     CloseCPort(state.tempPort);
  186. #else
  187.     DisposePort(state.tempPort);
  188. #endif
  189.     DisposeStdPixUPP((StdPixUPP)procs.newProc1);
  190.     
  191.     *dataOut    = state.data;
  192.     *idh        = state.idh;
  193.  
  194.     return err;
  195. }
  196.  
  197.  
  198. pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags )
  199. {
  200. #if TARGET_OS_MAC
  201. #pragma unused(srcRect,matrix,mode,mask,matte,matteRect,flags)
  202. #endif
  203.     extractPictRecord    *state;
  204.  
  205.     GetPort( (GrafPtr *)&state );
  206.  
  207.     if  ( state->idh == nil ) {
  208.         ImageDescriptionHandle    desc;
  209.         Ptr                     data;
  210.         long                    bufferSize;
  211.         OSErr                     err;
  212.         if ( (err=GetCompressedPixMapInfo(src, &desc, &data, &bufferSize, nil, nil)) == noErr ) {
  213.             state->idh = desc;
  214.             HandToHand( (Handle *)&state->idh );
  215.             PtrToHand( data, &state->data, bufferSize );
  216.         }
  217.     }
  218. }
  219.  
  220.  
  221. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap )
  222. {
  223.     ImageDescriptionHandle    desc = nil;
  224.     
  225.     if ( ( desc = (ImageDescription **)NewHandleClear(sizeof(ImageDescription)) ) != nil ) {
  226.         ImageDescription     *dp = *desc;
  227.         Rect                bounds = (**pixmap).bounds;
  228.  
  229.         dp->idSize             = sizeof(ImageDescription);
  230.         dp->cType             = cType;    
  231.         dp->spatialQuality     = codecNormalQuality;
  232.         dp->width            = bounds.right - bounds.left;
  233.         dp->height             = bounds.bottom - bounds.top;
  234.         dp->hRes             = 72L << 16;
  235.         dp->vRes             = 72L << 16;
  236.         dp->dataSize         = ((**pixmap).rowBytes & 0x3fff) * dp->height;
  237.         dp->depth             = (**pixmap).pixelSize;
  238.         dp->clutID             = -1;
  239.         
  240.         if ( SetImageDescriptionCTable( desc, (**pixmap).pmTable ) ) {
  241.             DisposeHandle( (Handle) desc );
  242.             desc = nil;
  243.         }
  244.     }
  245.     return desc;
  246. }
  247.  
  248. pascal void noDitherBitsProc(BitMap *srcBits, Rect *srcRect, Rect *dstRect, short mode, RgnHandle maskRgn);
  249. pascal void noDitherBitsProc(BitMap *srcBits, Rect *srcRect, Rect *dstRect, short mode, RgnHandle maskRgn)
  250. {
  251.     mode &= ~ditherCopy;
  252.     StdBits(srcBits, srcRect, dstRect, mode, maskRgn);
  253. }
  254.  
  255. //    DrawPictureNoDither is used to draw a QuickDraw picture but to turn convert any
  256. //    use of ditherCopy graphics modes to graphics modes that don't use ditherCopy. It
  257. //    only performs this with the stdbits bottleneck routine. Since ditherCopy is simply
  258. //    ORed in with other graphics modes, the replaced bottleneck routine only needs to
  259. //    AND off the ditherCopy flag.
  260. void DrawPictureNoDither(PicHandle pic, const Rect *bounds)
  261. {        
  262.     CQDProcs procs;
  263.     GrafPtr savePort;
  264.     CQDProcsPtr saveProcs;
  265.  
  266.     GetPort(&savePort);
  267. #ifdef TARGET_OS_WIN32
  268.     saveProcs = (CQDProcsPtr)savePort->grafProcs;
  269. #else
  270.     saveProcs = GetPortGrafProcs(savePort);
  271. #endif
  272.     SetStdCProcs( &procs );
  273.  
  274.     procs.bitsProc = (QDBitsUPP)NewQDBitsProc(noDitherBitsProc);
  275. #ifdef TARGET_OS_WIN32
  276.     savePort->grafProcs = (QDProcsPtr)&procs;
  277. #else
  278.     SetPortGrafProcs(savePort, &procs);
  279. #endif
  280.  
  281.     DrawPicture(pic, bounds);
  282.  
  283. #ifdef TARGET_OS_WIN32
  284.     savePort->grafProcs = (QDProcsPtr)saveProcs;
  285. #else
  286.     SetPortGrafProcs(savePort, saveProcs);
  287. #endif
  288.  
  289.     DisposeQDBitsUPP((QDBitsUPP)procs.bitsProc);
  290. }
  291.  
  292.  
  293. //
  294. // The following is a routine that can be used to clean up the colors in a picture
  295. // before being compressed with the Animation compressor in 16-bits at codecNormal
  296. // quality. The QuickTime Animation compressor can operate in both a lossless and
  297. // lossy manner. This routine is meant to help when compressing in a lossy manner.
  298. //
  299. // By clean up, what's meant is the forcing of any colors that are sufficiently close
  300. // to white to colors that are not as close. Since the Animation compressor will
  301. // perform threshholding of the image's colors when codecNormal quality is specified,
  302. // without this preprocessing, colors very close to white can be mapped to white
  303. // in the compression. If white was chosen as the key color, pixels that are
  304. // close to white could possibly become transparent as well.
  305. //
  306. // While not used by other routines in this file, prepareFor16BitCompress is provided
  307. // as an example of how this might be done.
  308. //
  309. // Note that with codecLossless quality, there is no remapping of colors so this
  310. // step is unnecessary.
  311. //
  312.  
  313. #define kThreshold (255 - 16)
  314.  
  315. OSErr prepareFor16BitCompress(PicHandle *pic)
  316. {
  317.     OSErr err = noErr;
  318.     PicHandle newPicture = nil;
  319.     Rect r;
  320.     GWorldPtr gw = nil;
  321.     CGrafPtr savePort;
  322.     GDHandle saveGD;
  323.     short rowBytes;
  324.     Ptr baseAddr;
  325.     long w, h;
  326.     PixMapHandle pm;
  327.  
  328.     GetGWorld(&savePort, &saveGD);
  329.  
  330.     r = (***pic).picFrame;
  331.     MacOffsetRect(&r, (short)-r.left, (short)-r.top);
  332.  
  333.     err = NewGWorld(&gw, 32, &r, nil, nil, useTempMem);
  334.     if (err) {
  335.         err = NewGWorld(&gw, 32, &r, nil, nil, 0);
  336.         if (err) goto bail;
  337.     }
  338.  
  339.     pm = GetGWorldPixMap(gw);
  340.     LockPixels(pm);
  341.     SetGWorld(gw, nil);
  342.     EraseRect(&r);
  343.  
  344.     DrawPicture(*pic, &r);
  345.  
  346.     baseAddr = GetPixBaseAddr(pm);
  347.     rowBytes = (**pm).rowBytes & 0x3fff;
  348.     for (h=0; h<r.bottom; h++) {
  349.         long *pixelPtr = (long *)baseAddr;
  350.  
  351.         for (w=0; w<r.right; w++, pixelPtr++) {
  352.             UInt8 r, g, b, a;
  353.             long pixel = *pixelPtr;
  354.  
  355.             if ((pixel & 0x0ffffff) == 0x00ffffff)        // pure white
  356.                 continue;
  357.  
  358.             a = (pixel >> 24) & 0x0ff;
  359.             r = (pixel >> 16) & 0x0ff;
  360.             g = (pixel >>  8) & 0x0ff;
  361.             b = (pixel >>  0) & 0x0ff;
  362.             if ((r > kThreshold) && (g > kThreshold) && (b > kThreshold)) {
  363.                 r = g = b = kThreshold;
  364.                 *pixelPtr = (a << 24) | (kThreshold << 16) | (kThreshold << 8) | (kThreshold << 0);
  365.             }
  366.         }
  367.  
  368.         baseAddr += rowBytes;
  369.     }
  370.  
  371.     newPicture = OpenPicture(&r);
  372.     CopyBits((BitMap *)&pm, (BitMap *)&pm, &r, &r, ditherCopy, nil);
  373.  
  374.     ClosePicture();
  375.     UnlockPixels(pm);
  376.  
  377. bail:
  378.     if (gw)
  379.         DisposeGWorld(gw);
  380.  
  381.     if (err == noErr) {
  382.         if (newPicture) {
  383.             KillPicture(*pic);
  384.             *pic = newPicture;
  385.         }
  386.     }
  387.  
  388.     SetGWorld(savePort, saveGD);
  389.  
  390.     return err;
  391. }
  392.  
  393.  
  394. /*
  395.     ---------------- Callback based routines for compressing with hittesting and transparency ----------------
  396.  */
  397.  
  398. /*
  399.     RecompressWithTransparencyFromProc
  400.     
  401.     This is a routine either called indirectly through RecompressCompressedImageWithTransparency, 
  402.     RecompressPictureWithTransparency, or RecompressPictureFileWithTransparency or called directly.
  403.     It takes a callback procedure which is responsible for returning the dimensions of the
  404.     area of some type of drawable entity and for actually drawing that entity.
  405.     
  406.         includeHitTesting        TRUE if hit testing data should be added to the compressed data
  407.         keyColor                A RGBColor that should be used as the transparency color. Pass nil
  408.                                 if the image doesn't have transparent portions.
  409.         hitTestRegion            A RgnHandle specifying an area that is to be used as the hit test
  410.                                 area. If you pass this, you must also set includeHitTesting to TRUE.
  411.                                 This is optional as the callback procedure can perform drawing
  412.                                 itself of the hit test area which is often suitable when both the
  413.                                 image and hit test area were painted in a drawing program.
  414.         idh                        Returned ImageDescriptionHandle for the compressed image data
  415.         imageData                Returned Handle to the compressed image data
  416.  
  417.  */
  418. OSErr RecompressWithTransparencyFromProc( CompressDrawProc drawProc, void * drawProcRefcon, 
  419.                                                     Boolean includeHitTesting,
  420.                                                     RGBColor *keyColor, 
  421.                                                     RgnHandle hitTestRegion,
  422.                                                     ImageDescriptionHandle *idh, Handle * imageData )
  423. {
  424.     OSErr                         err = noErr;
  425.     Rect                        bounds;
  426.     CGrafPtr                    savePort;
  427.     GDHandle                    saveDevice;
  428.     GWorldPtr                    gwImage = nil;        // always used
  429.     GWorldPtr                    gwPrev = nil;        // used if compressing with transparency (via keycolor)
  430.     GWorldPtr                    gwMap = nil;        // used if compressing with hittesting data
  431.     ImageDescriptionHandle        desc = nil;            // resulting image description
  432.     ImageDescriptionHandle        gwMapDesc = nil;
  433.     ImageSequence                seq = 0;            // compress sequence
  434.     ImageSequenceDataSource        mapSource = 0L;
  435.     Ptr                            data = nil;
  436.     long                         dataSize;
  437.     UInt8                         similarity;
  438.     Boolean                        includeTransparency = false;
  439.     RGBColor                    saveBackColor;
  440.         
  441.     GetGWorld( &savePort, &saveDevice );
  442.     
  443.     if( !drawProc || !idh || !imageData ){
  444.         err = paramErr;
  445.         goto bail;
  446.     }
  447.     
  448.     // tell callback that it should initialize any storage it needs
  449.     err = drawProc( kRecoProcInitMsg, nil, nil, 0, drawProcRefcon );
  450.     if(err) goto bail;
  451.     
  452.     // determine bounds to use for compression
  453.     err = drawProc( kRecoProcGetBoundsMsg, &bounds, nil, 0, drawProcRefcon );
  454.     if(err) goto bail;
  455.     
  456.     err = QTNewGWorld(&gwImage, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  457.     if(err) goto bail;
  458.  
  459.     if( keyColor ) {
  460.         includeTransparency = true;
  461.     }
  462.     
  463.     // Include hit testing? If so, we need a previous buffer and an 8-bit GWorld for the mask data
  464.     if( includeHitTesting ) {
  465.         err = QTNewGWorld(&gwPrev, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  466.         if(err) goto bail;
  467.  
  468.         err = QTNewGWorld(&gwMap, 8, &bounds, nil, nil, kICMTempThenAppMemory);
  469.         if(err) goto bail;
  470.     }
  471.     
  472.     LockPixels( GetGWorldPixMap(gwImage) );
  473.     
  474.     if( gwPrev )
  475.         LockPixels( GetGWorldPixMap(gwPrev) );
  476.     
  477.     if( gwMap )
  478.         LockPixels( GetGWorldPixMap(gwMap) );
  479.     
  480.     if(gwPrev) {
  481.         SetGWorld( gwPrev, nil );
  482.         ClipRect( &bounds );
  483.         
  484.         GetBackColor( &saveBackColor );
  485.         if( keyColor )
  486.             RGBBackColor( keyColor );
  487.         
  488.             EraseRect( &bounds );
  489.             
  490.         RGBBackColor( &saveBackColor );
  491.     }
  492.     
  493.     if( gwMap ) {
  494.         SetGWorld( gwMap, nil );
  495.         
  496.         EraseRect( &bounds );            // paint background white
  497.  
  498.         err = drawProc( kRecoProcDrawMsg, &bounds, gwMap, kRecoProcHitTestingImageType, drawProcRefcon );
  499.         if(err) goto bail;
  500.         
  501.         if( hitTestRegion ) {
  502.             RGBColor blackRGB;
  503.             
  504.             blackRGB.red = blackRGB.green = blackRGB.blue = 0;
  505.             
  506.             RGBForeColor( &blackRGB );
  507.             MacPaintRgn( hitTestRegion );
  508.         }
  509.  
  510.         gwMapDesc = createImageDescription(kRawCodecType, GetGWorldPixMap(gwMap));
  511.         err = MemError();
  512.         if(err) goto bail;
  513.     }
  514.     
  515.     SetGWorld( gwImage, nil );
  516.     ClipRect( &bounds );
  517.     EraseRect( &bounds );
  518.     
  519.     desc = (ImageDescriptionHandle) NewHandle(sizeof(ImageDescription));
  520.  
  521.  
  522.     // NOTE: We pass codecLosslessQuality so that the key color if any is matched exactly. This avoids colors within
  523.     // some threshhold different from the key color being taken as equivalent to the key color. Alternatively, we
  524.     // could perform some threshhold processing on the source image's pixels and pass codecNormalQuality.
  525.     if( includeHitTesting ) {
  526.         // Allocate a compression sequence and add source data for hittest mask
  527.         err = CompressSequenceBegin(&seq, GetGWorldPixMap(gwPrev), nil, nil, nil, kCompressDepth, kAnimationCodecType, 
  528.                                             anyCodec, codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc);
  529.  
  530.         // with hit testing, we have to add a data source to hold the mask data
  531.         err = CDSequenceNewDataSource(seq, &mapSource, kRecoProcHitTestingImageType, 1, (Handle)gwMapDesc, nil, nil);
  532.         if (err) goto bail;
  533.  
  534.         err = CDSequenceSetSourceData(mapSource, GetPixBaseAddr(GetGWorldPixMap(gwMap)), (**gwMapDesc).dataSize);
  535.         if (err) goto bail;
  536.  
  537.         // What's the maximum size the compressed data could be--including hit-test data?
  538.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwPrev), &dataSize);
  539.     }
  540.     else
  541.     {    // not hit-testing so we only need the image buffer
  542.         err = CompressSequenceBegin( &seq, GetGWorldPixMap(gwImage), nil, &bounds, nil, kCompressDepth, kAnimationCodecType, 0, 
  543.                                     codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc );
  544.         if(err) goto bail;
  545.         
  546.         // What's the maximum size the compressed data could be?
  547.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwImage), &dataSize);
  548.     }
  549.     if (err) goto bail;
  550.     
  551.  
  552.     data = NewPtr( dataSize );
  553.     if(noErr != (err = MemError())) goto bail;
  554.     
  555.     if( includeHitTesting /* with or without transparency */ ) {
  556.         // With hittesting, we use two buffers. Actually we don't have to but do so to show how it can be
  557.         // done. Also, this code was based upon some older code that did.
  558.         
  559.         
  560.         // compress the GWorld painted with the keyColor exclusively
  561.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwPrev), nil, 0, data, &dataSize, &similarity, nil );
  562.         if ( err ) goto bail;
  563.  
  564.         err = SetCSequencePrev(seq, GetGWorldPixMap(gwPrev), nil);
  565.         if (err) goto bail;
  566.  
  567.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  568.         // areas it doesn't paint will be in the key color
  569.         SetGWorld( gwImage, nil );
  570.         
  571.         GetBackColor( &saveBackColor );
  572.         if( keyColor )
  573.             RGBBackColor( keyColor );
  574.             
  575.             EraseRect( &bounds );
  576.         
  577.         RGBBackColor( &saveBackColor );
  578.     
  579.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  580.         if(err) goto bail;
  581.  
  582.         // now compress the GWorld holding the image drawn on top of the keyColor
  583.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil);
  584.         if (err) goto bail;
  585.         
  586.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  587.         // Also, hit testing data is contained in the image data if it was specified.
  588.     }
  589.     else if( includeTransparency ) {
  590.         // For transparency case without hittesting, we get by with only using a single buffer so we special case the
  591.         // code here. This is also for clarity.
  592.     
  593.         // compress the GWorld painted with the keyColor exclusively
  594.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil );
  595.         if ( err ) goto bail;
  596.  
  597.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  598.         // areas it doesn't paint will be in the key color
  599.         SetGWorld( gwImage, nil );
  600.         
  601.         GetBackColor( &saveBackColor );
  602.         if( keyColor )
  603.             RGBBackColor( keyColor );
  604.             
  605.             EraseRect( &bounds );
  606.         
  607.         RGBBackColor( &saveBackColor );
  608.     
  609.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  610.         if(err) goto bail;
  611.  
  612.         // now compress the GWorld holding the image drawn on top of the keyColor
  613.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil);
  614.         if (err) goto bail;
  615.         
  616.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  617.         // Also, hit testing data is contained in the image data if it was specified.
  618.     }
  619.     else
  620.     {
  621.         SetGWorld( gwImage, nil );
  622.  
  623.         // draw the image into the GWorld
  624.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  625.         if(err) goto bail;
  626.  
  627.         // compress the GWorld containing the image painted on white
  628.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil );
  629.         if ( err ) goto bail;
  630.         
  631.         // At this point, data points to the image data for just the image, newly compressed. Also, hit testing data is contained
  632.         // in the image data if it was specified.
  633.     }
  634.     
  635.     CDSequenceEnd( seq );
  636.     seq = 0;
  637.     
  638.     // free the GWorlds and drop references so we have more memory for PtrToHand
  639.     if( gwImage )    DisposeGWorld( gwImage );
  640.     gwImage = nil;
  641.     if( gwMap )    DisposeGWorld( gwMap );
  642.     gwMap = nil;
  643.     if( gwPrev ) DisposeGWorld( gwPrev );
  644.     gwPrev = nil;
  645.     
  646.     err = PtrToHand( data, imageData, dataSize );
  647.     if ( err ) goto bail;
  648.     
  649.     *idh = desc;
  650.     desc = nil;                // forget about this name for ImageDescriptionHandle so dispose below doesn't catch it
  651.     
  652. bail:
  653.     // tell callback to dispose of anything it allocated. We pass 'err ' in portType if an error occurred
  654.     drawProc( kRecoProcDisposeMsg, nil, nil, err ? FOUR_CHAR_CODE('err ') : 0, drawProcRefcon );
  655.     
  656.     CDSequenceEnd( seq );
  657.     SetGWorld( savePort, saveDevice );
  658.     
  659.     if(gwImage)        DisposeGWorld( gwImage );
  660.     if(gwMap )        DisposeGWorld( gwMap );
  661.     if(gwPrev )        DisposeGWorld( gwPrev );
  662.     if(desc)         DisposeHandle((Handle) desc );
  663.     if(gwMapDesc)    DisposeHandle((Handle) gwMapDesc );
  664.     if(data)        DisposePtr( data );
  665.         
  666.     return err;
  667. }
  668.  
  669.  
  670. /*
  671.     myPictureCompressDrawProc
  672.     
  673.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickDraw Pictures.
  674.  */
  675.  
  676. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  677. {
  678. #if TARGET_OS_MAC
  679. #pragma unused(drawingPort)
  680. #endif
  681.     OSErr err = noErr;
  682.     PictureCompressProcData * data = refcon;
  683.     Rect r;
  684.  
  685.     switch( message ) {
  686.         case kRecoProcInitMsg:
  687.             break;
  688.             
  689.         case kRecoProcDisposeMsg:
  690.             break;
  691.             
  692.         case kRecoProcGetBoundsMsg:
  693.             r = (**data->picture).picFrame;
  694.             
  695.             r.left = EndianS16_BtoN(r.left);
  696.             r.top = EndianS16_BtoN(r.top);
  697.             r.bottom = EndianS16_BtoN(r.bottom);
  698.             r.right = EndianS16_BtoN(r.right);
  699.             
  700.             MacOffsetRect(&r, (short)-r.left, (short)-r.top );
  701.             
  702.             *bounds = r;
  703.             break;
  704.             
  705.         case kRecoProcDrawMsg:
  706.             r = (**data->picture).picFrame;
  707.             
  708.             r.left = EndianS16_BtoN(r.left);
  709.             r.top = EndianS16_BtoN(r.top);
  710.             r.bottom = EndianS16_BtoN(r.bottom);
  711.             r.right = EndianS16_BtoN(r.right);
  712.  
  713.             MacOffsetRect( &r, (short)-r.left, (short)-r.top );
  714.  
  715.             if( kRecoProcOriginalImageType == drawingImageType )
  716.                 DrawPictureNoDither( data->picture, &r );
  717.             break;
  718.         default:
  719.             err = -1;
  720.     }
  721.  
  722.     return err;
  723. }    
  724.     
  725.  
  726. /*
  727.     myImageCompressDrawProc
  728.     
  729.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickTime compressed image data.
  730.  */
  731. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  732. {
  733. #if TARGET_OS_MAC
  734. #pragma unused(drawingImageType)
  735. #endif
  736.  
  737.     OSErr err = noErr;
  738.     CompressedImageCompressProcData * data = refcon;
  739.     Rect r;
  740.     
  741.     switch( message ) {
  742.     case kRecoProcInitMsg:
  743.         break;
  744.     case kRecoProcDisposeMsg:
  745.         break;
  746.     case kRecoProcGetBoundsMsg:
  747.         r.left = r.top = 0;
  748.         r.right = (**data->imageDesc).width;
  749.         r.bottom = (**data->imageDesc).height;
  750.         
  751.         *bounds = r;
  752.         break;
  753.     case kRecoProcDrawMsg:
  754.         {
  755.             SignedByte saveState;
  756.             
  757.             r.left = r.top = 0;
  758.             r.right = (**data->imageDesc).width;
  759.             r.bottom = (**data->imageDesc).height;
  760.             
  761.             saveState = HGetState( data->imageData );
  762.             HLockHi( data->imageData );
  763.             
  764.             if( kRecoProcOriginalImageType == drawingImageType )
  765.                 err = DecompressImage( *data->imageData, data->imageDesc, GetGWorldPixMap(drawingPort), &r, &r, srcCopy, nil );
  766.             
  767.             HSetState( data->imageData, saveState );
  768.         }
  769.         break;
  770.     default:
  771.         err = -1;
  772.     }
  773.  
  774.     return err;
  775. }    
  776.  
  777.  
  778.  
  779. /*
  780.     RecompressCompressedImageWithTransparency
  781.     
  782.     Given an ImageDescriptionHandle and a handle to image data, generate new RLE compressed data
  783.     with optional hitTesting and transparency.
  784.  */
  785. OSErr RecompressCompressedImageWithTransparency( ImageDescriptionHandle originalDesc, Handle originalImageData,
  786.                                         RGBColor *keyColor, 
  787.                                         RgnHandle hitTestRegion,
  788.                                         ImageDescriptionHandle *idh, Handle * imageData )
  789. {
  790.     OSErr err = noErr;
  791.     CompressedImageCompressProcData params;
  792.     
  793.     params.imageDesc = originalDesc;
  794.     params.imageData = originalImageData;
  795.     
  796.     err = RecompressWithTransparencyFromProc( myImageCompressDrawProc, ¶ms, 
  797.                                         (Boolean)(hitTestRegion != nil), 
  798.                                         keyColor, 
  799.                                         hitTestRegion, 
  800.                                         idh, imageData );
  801.     
  802.     return err;
  803. }
  804.  
  805. /*
  806.     RecompressPictureWithTransparency
  807.     
  808.     Given a QuickDraw PicHandle, generate new RLE compressed data with optional hitTesting and transparency.
  809.  */
  810. OSErr RecompressPictureWithTransparency( PicHandle originalPicture,
  811.                                         RGBColor *keyColor, 
  812.                                         RgnHandle hitTestRegion,
  813.                                         ImageDescriptionHandle *idh, Handle * imageData )
  814. {
  815.     OSErr err = noErr;
  816.     PictureCompressProcData params;
  817.     
  818.     params.picture = originalPicture;
  819.     
  820.     err = RecompressWithTransparencyFromProc( myPictureCompressDrawProc,
  821.                                             ¶ms, 
  822.                                             (Boolean)(hitTestRegion != nil), 
  823.                                             keyColor, 
  824.                                             hitTestRegion, 
  825.                                             idh,
  826.                                             imageData );
  827.     
  828.     return err;
  829. }
  830.  
  831. /*
  832.     RecompressPictureFileWithTransparency
  833.     
  834.     Given a QuickDraw PICT file, generate new RLE compressed data with optional hitTesting and transparency.
  835.     This function uses GetCompressedImageFromPicture to do the actual work on the PicHandle retrieved from
  836.     the PICT file.
  837.  */
  838. OSErr RecompressPictureFileWithTransparency( FSSpec * spec, 
  839.                                         RGBColor *keyColor, 
  840.                                         RgnHandle hitTestRegion,
  841.                                         ImageDescriptionHandle *idh, Handle * imageData )
  842. {
  843.     OSErr         err = noErr;
  844.     short        sourceRefNum = 0;
  845.     PicHandle    picture = nil;
  846.     long        eof;
  847.     long        countBytes;
  848.     
  849.     *idh = nil;
  850.     *imageData = nil;    
  851.     
  852.     BailOSErr(FSpOpenDF( spec, fsRdPerm, &sourceRefNum ));
  853.     
  854.     BailOSErr(GetEOF( sourceRefNum, &eof ));
  855.     eof -= 512;
  856.     
  857.     BailOSErr(SetFPos( sourceRefNum, fsFromStart, 512 ));
  858.             
  859.     picture = (PicHandle) NewHandle(eof);
  860.     err = MemError();
  861.     BailOSErr(err);
  862.  
  863.     countBytes = eof;
  864.     HLock((Handle) picture);
  865.     BailOSErr( FSRead( sourceRefNum, &countBytes, *picture) );
  866.     HUnlock((Handle) picture);
  867.     
  868.     BailOSErr( RecompressPictureWithTransparency( picture,  keyColor, hitTestRegion,
  869.                                 idh, imageData ));
  870.                                 
  871. bail:
  872.     if ( picture )            DisposeHandle((Handle) picture );
  873.     if ( sourceRefNum )        FSClose( sourceRefNum );
  874.         
  875.     return err;
  876. }
  877.  
  878. #endif
  879.